#!usr/bin/env python3
#  encoding:utf-8
import cv2 as cv
import copy
import numpy as np
import matplotlib.pyplot as plt

# 打开图像
filename = r'E:\python\rice.jpg'
#filename = r'E:\python\IMG_20200505_143744.jpg'


image = cv.imread(filename,flags=1)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("image", image)
cv.imshow("gray",gray)


thr, dst = cv.threshold(gray, 0, 0xff, cv.THRESH_OTSU)# 大津算法灰度阈值化
print('Threshold is :', thr)
#dst = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 101, 1)  # 局部大津算法


# 画出灰度直方图
plt.hist(gray.ravel(), 256, [0, 256])
plt.show()

element = cv.getStructuringElement(cv.MORPH_CROSS, (3,3))
bw = cv.morphologyEx(dst, cv.MORPH_OPEN, element)

seg = copy.deepcopy(bw)
# 计算轮廓
img,cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

count = 0
area_array=np.array([])#米粒面积数组
line_array=np.array([])#米粒长度数组
# 遍历所有区域，并去除面积过小的
for i in range(len(cnts), 0, -1):
    c = cnts[i-1]
    area = cv.contourArea(c)#米粒面积
    if area < 10:
        continue
    count = count + 1
    area_array=np.append(area_array,area)
    minAreaRect=cv.minAreaRect(c)#米粒边界
    x,y,z,h=cv.boxPoints(minAreaRect)#米粒的四个坐标

    #米粒的长度
    l1=((x[0]-y[0])**2+(x[1] - y[1]) ** 2)**0.5
    l2= ((x[0] - h[0]) ** 2 + (x[1] - h[1]) ** 2) ** 0.5
    if l1>l2:
        line=l1
    else:
        line=l2
    print("米粒", i, "面积" ,area,"长度",round(line,2))
    line_array=np.append(line_array,line)
    cv.line(image,tuple(x),tuple(y),(255,0,0),1)
    cv.line(image, tuple(y), tuple(z), (255, 0, 0), 1)
    cv.line(image, tuple(z), tuple(h), (255, 0, 0), 1)
    cv.line(image, tuple(h), tuple(x), (255, 0, 0), 1)

    # 区域画框并标记
  #  x, y, w, h = cv.boundingRect(c)
   # cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 0xff), 1)
    cv.putText(image, str(count), (x[0], x[1]), cv.FONT_HERSHEY_PLAIN,0.5, (0, 0xff, 0))

print("米粒数量： ", count)
area_all=area_array.sum()
print("总面积:",round(area_all,3))
area_average=area_all/count
print("平均面积:",round(area_average,3))
print("lflf"*10,"\n")
std=area_array.std()
print("面积标准差:",round(std,3))
area1=area_average-std*1.5

area2=area_average+std*1.5
print("面积3sigma的取值范围",round(area1,3),"~",round(area2,3))

count1=0
for i in area_array:
    if i>area1 and i<area2:
        count1+=1
print("米粒在3sigma内的数量为：",count1,"\n")
print("--lf华丽的分割线--"*4,"\n")

line_all=line_array.sum()
print("总长度：",line_all)
line_average=line_all/count
print("平均长度：",line_average)
std_line=line_array.std()
print("长度标准差：",std_line)
line1=line_average-std_line*1.5
line2=line_average+std_line*1.5
print("长度3sigma的取值范围是",round(line1,3),"~",round(line2,3))
count2=0
for j in line_array:
    if j<line2 and j>line1:
        count2+=1
print("米粒在3sigma内的数量为：",count2)

cv.imshow("fengetu",image)
cv.imshow("yuzhitu", bw)

cv.waitKey()
cv.destroyAllWindows()